package wx.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.pig4cloud.pigx.common.oss.OssProperties;
import com.pig4cloud.pigx.common.oss.service.OssTemplate;
import lombok.extern.slf4j.Slf4j;
import net.xnzn.framework.id.Id;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import wx.ex.QRCodeCreateException;

import java.io.ByteArrayInputStream;
import java.util.Map;

@RefreshScope
@Slf4j
@Service
public class UnlimitedQRCodeService {
    @Autowired
    MiniTokenService miniTokenService;
    @Autowired
    OssTemplate ossTemplate;
    @Autowired
    OssProperties ossProperties;
    @Value("${qr-code-page:}")
    private String qrCodePage;

    public String getQRCodeUrl(String scene) throws Exception {
        try {
            Map<String, Object> param = Maps.newHashMap();
            param.put("page", qrCodePage);
            param.put("scene", scene);

            HttpResponse response = HttpRequest.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + miniTokenService.getAccessToken())
                    .body(JSON.toJSONString(param))
                    .execute();
            if (response.bodyBytes() == null) {
                throw new QRCodeCreateException("获取小程序二维码错误");
            }

            final String objectName = "qrCode/" + Id.nextString() + ".jpg";
            ossTemplate.putObject(ossProperties.getBucketName(), objectName, new ByteArrayInputStream(response.bodyBytes()));
            return "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + objectName;
        } catch (Exception e) {
            log.error("获取小程序二维码错误， 错误信息：{}", e.getMessage());
            throw e;
        }
    }
}
